/****************
 *@description:  库存盘点  procurement/stockInventory/index
 *@author: Xhd
 *@date: 2023-07-25 15:08:51
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Button, Tabs, Modal } from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import { apiStockTakeListPage, apiStockTakeListDel, apiStockTakeListAddBefore, apiStockLibraryGoodsActivityWait, apiStockLibraryGoodsPage, apiStockLibraryGoodsList, apiStockLibraryGoodsDetilList, apiPostVoucherCode } from '@/request/procurement/stock.js'
import { exportSheetTable } from '@/utils/exportTable'
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"

const { Option } = Select
const status = [{ label: '草稿', value: 0, color: 'black' }, { label: '未审核', value: 1, color: "orange" }, { label: '已审核', value: 2, color: "#1890ff" }, { label: '已驳回', value: 3, color: "#cccccc" }]

class Stock extends Component {
  constructor() {
    super()
    // this.formRef_check = React.createRef()
    // this.formRef_store = React.createRef()
    this.queryFormRef_check = React.createRef()
    this.queryFormRef_store = React.createRef()
    this.state = {
      dataSource: [],
      columnsCheck: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          render: (text, record, index) => {
            return ((this.state.pageDataCheck.pageNo - 1) * (this.state.pageDataCheck.pageSize) + (index + 1));
          }
        },
        {
          title: "盘点单号",
          dataIndex: "code",
          key: "code",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "盘点日期",
          dataIndex: "createTime",
          key: "createTime",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "仓库名称",
          dataIndex: "libraryName",
          key: "libraryName",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "凭证编码",
          dataIndex: "voucherCode",
          key: "voucherCode"
        },
        {
          title: "登记人",
          dataIndex: "userName",
          key: "userName",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "审批人",
          dataIndex: "checkName",
          key: "checkName",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "审批时间",
          dataIndex: "checkedTime",
          key: "checkedTime",
          render: (text, render) => {
            return text
          }
        },
        {
          title: "状态",
          dataIndex: "status",
          key: "status",
          render: (text, render) => {
            let obj = status.find(item => item.value == text);
            return obj === undefined ? '' : <div style={{ color: obj.color }}>
              {obj.label}
            </div>
          }
        },
        {
          title: "操作",
          dataIndex: "serviceShowFile",
          key: "serviceShowFile",
          fixed: 'right',
          render: (text, render) => {
            return <div>
              <TheButton haspermi={['storage:stockCheck:voucher']} onClick={() => this.voucher(render)}>编辑凭证</TheButton>
              <TheButton haspermi={['storage:stockCheck:view']} onClick={() => this.opreate('normal', render.id)}>查看详情</TheButton>
              {
                render.status === 0 &&
                <TheButton haspermi={['storage:stockCheck:edit']} onClick={() => this.opreate('edit', render.id)}>编辑</TheButton>
              }
              {
                render.status === 1 ?
                  <TheButton haspermi={['storage:stockCheck:execute']} onClick={() => this.opreate('execute', render.id)}>审核</TheButton> : null
              }
              {
                render.status === 0 && <TheButton haspermi={['storage:stockCheck:del']} onClick={() => this.del(render.id)} >删除</TheButton>
              }
            </div>
          }
        },
      ],
      newColumns_check: [],
      form_show_check: true,
      searchOption_check: [
        { field: 'code', label: '盘点单号', placeholder: '盘点单号', required: false, rules: [], type: 'Input', defaultValue: '' },

        { field: 'libraryName', label: '仓库名称', placeholder: '仓库名称', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
        // { field: 'status', label: '状态', placeholder: '状态', required: false, rules: [], type: 'Select', options: status, defaultValue: '' },
      ],
      queryForm_check: {},
      dataSourceCheck: [],
      totalCheck: 0,
      libraryName_check: '',
      librarys: [],
      pageDataCheck: {
        pageNo: 1,
        pageSize: 10
      },
      visible: false,
      vouchercode: ''
    }
  }
  componentDidMount() {
    this.setState({
      newColumns_check: this.state.columnsCheck,
    })
    let searchParams = store.getState().searchValue
    let { queryForm_check, pageNoC, pageSizeC, pathName } = searchParams
    this.queryFormRef_check.onSetDefault({
      ...queryForm_check
    })
    if (searchParams && pathName == 'check') {
      this.setState({
        queryForm_check,
        pageDataCheck: {
          pageNo: pageNoC, pageSize: pageSizeC
        }
      }, () => {
        this.getCheckPage()
      })
    } else {
      this.getCheckPage()
    }
  }
  goGoods(id) {
    this.props.history.push('/storageManager/goodsStore/' + id)
  }
  opreate(type, id) {
    this.props.history.push('/storageManager/takeStock/' + id + "/" + type)
  }

  onViewZhanYong(record) {
    apiStockLibraryGoodsActivityWait({ libraryGoodsId: record.id }).then(res => {
      if (res.code === 0) {
        alert(res.data)
      }
    })
  }
  // 盘点
  getCheckPage(values) {
    this.setState({
      queryForm_check: values === undefined ? this.state.queryForm_check : { ...values }
    }, async () => {
      let { pageNo, pageSize } = this.state.pageDataCheck
      let params = {
        pageNoC: this.state.pageDataCheck.pageNo,
        pageSizeC: this.state.pageDataCheck.pageSize,
        queryForm_check: this.state.queryForm_check,
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'check',
          ...params
        }
      })
      let res = await apiStockTakeListPage({ pageNo, pageSize, ...this.state.queryForm_check })
      if (res.code === 0) {
        this.setState({
          dataSourceCheck: res.data,
          totalCheck: res.totalCount
        })
      }
    })
  }

  pageChangeCheck = (pageNo, pageSize) => {
    this.setState({
      // libraryName_check: values.libraryName?values.libraryName:null,
      pageDataCheck: {
        pageNo, pageSize
      }
    }, () => {
      this.getCheckPage()
    })
  };

  onReset_check = () => {
    this.setState({
      queryForm_check: {}
    }, () => {

      this.pageChangeCheck(1, 10)
    })
  }

  async del(id) {
    React.$confirm({
      title: "提示",
      type: 'warning',
      content: "确定是否删除？",
      onOk: async () => {
        let res = await apiStockTakeListDel({ id })
        if (res.code === 0) {
          this.pageChangeCheck(1, 10)
          React.$message({
            type: 'success',
            content: res.codeMessage
          })
        } else {
          React.$message({
            type: 'warning',
            content: res.codeMessage
          })
        }
      }
    });

  }
  onFinishCheck = () => {
    let values = this.formRef_check.current.getFieldsValue()
    this.setState({
      libraryName_check: values.libraryName ? values.libraryName : '',
    }, () => {
      this.pageChangeCheck(1, 10)
    })
  }

  onFormSearch_check(values) {
    this.setState({
      pageDataCheck: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getCheckPage(values)
    })
  }
  voucher = (value) => {
    this.setState({
      visible: true,
      id: value.id,
      vouchercode: value.voucherCode
    })
  }
  handleCancel = () => {
    this.setState({
      visible: false,
    })
  };
  editVoucher = async (values) => {
    const { id } = this.state
    let res = await apiPostVoucherCode({ id, ...values })
    if (res.code === 0) {
      React.$message({
        type: 'warning',
        content: res.codeMessage
      })
      this.handleCancel()
      this.getCheckPage()
    }
  }
  render() {
    let { columnsCheck,
      dataSourceCheck, pageDataCheck, totalCheck,
      form_show_check, searchOption_check, newColumns_check,
      visible, vouchercode
    } = this.state
    return (
      <div className="p-layout-box commodity-examine">
        <TheQueryForm ref={(ref) => this.queryFormRef_check = ref} show={form_show_check} option={searchOption_check}
          onReset={() => this.onReset_check()}
          onGetValues={(values) => this.onFormSearch_check(values)} >
        </TheQueryForm>
        <TheTableExtend
          columns={columnsCheck}
          onFormTrigger={() => this.setState({ form_show_check: !this.state.form_show_check })}
          onTableRefresh={() => this.getCheckPage()}
          onColumnsFilter={(value) => this.setState({
            newColumns_check: value
          })}
        >
          <TheButton haspermi={['storage:stockCheck:add']} size="middle" onClick={() => this.props.history.push('/storageManager/takeStock/null/add')} type="primary">新增</TheButton>
        </TheTableExtend>
        <TheTable
          scroll={{ x: "max-content", y: '63vh' }}
          columns={newColumns_check}
          dataSource={dataSourceCheck}
        />
        <ThePagination
          pageNo={pageDataCheck.pageNo}
          pageSize={pageDataCheck.pageSize}
          total={totalCheck}
          pageChange={this.pageChangeCheck}
        />
        <Modal
          title={"编辑凭证编号"}
          visible={visible}
          footer={null}
          onCancel={() => this.handleCancel()}>
          <Form onFinish={(values) => this.editVoucher(values)}>
            <Form.Item label="凭证编码" name={'voucherCode'} >
              <Input defaultValue={vouchercode} />
            </Form.Item>
            <Form.Item>
              <Button type="default" onClick={() => this.handleCancel()} style={{ 'marginRight': 20 }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div >
    );
  }
}
export default Stock
